package manager

import android.graphics.Bitmap
import app.AppContext
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.common.BitMatrix
import com.google.zxing.qrcode.QRCodeWriter
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import com.hontech.kdxclient.R

object BarcodeManager {
    private val WIDTH = AppContext.resources.getDimension(R.dimen.x200).toInt()
    private val HEIGHT = AppContext.resources.getDimension(R.dimen.y200).toInt()
    private val qrCodeWriter = QRCodeWriter()
    private val hintTypeMap = HashMap<EncodeHintType, Any>()

    init {
        hintTypeMap[EncodeHintType.CHARACTER_SET] = "utf-8"
        hintTypeMap[EncodeHintType.MARGIN] = 1
        hintTypeMap[EncodeHintType.ERROR_CORRECTION] = ErrorCorrectionLevel.H
    }

    fun create(content: String, width: Int = WIDTH, height: Int = HEIGHT): Bitmap {
        val matrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hintTypeMap)
        val pixel = IntArray(width * height)
        val resMatrix = deleteWhite(matrix)
        val w = resMatrix.width
        val h = resMatrix.height
        for (i in 0 until h) {
            for (j in 0 until w) {
                if (resMatrix.get(j, i)) {
                    pixel[i * w + j] = 0x00
                } else {
                    pixel[i * w + j] = 0xFFFFFFFF.toInt()
                }
            }
        }
        return Bitmap.createBitmap(pixel, w, h, Bitmap.Config.RGB_565)
    }

    private fun deleteWhite(matrix: BitMatrix): BitMatrix {
        val rec = matrix.enclosingRectangle
        val resWidth = rec[2] + 1
        val resHeight = rec[3] + 1
        val resMatrix = BitMatrix(resWidth, resHeight)
        resMatrix.clear()
        for (i in 0 until resWidth) {
            for (j in 0 until resHeight) {
                if (matrix.get(i + rec[0], j + rec[1])) {
                    resMatrix.set(i, j)
                }
            }
        }
        return resMatrix
    }
}